using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using SerialTool.Models;
using SerialTool.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace SerialTool.ViewModels;

public partial class ProtocolConfigViewModel : ViewModelBase
{
    private readonly MainWindowViewModel _mainViewModel;
    
    // 可用协议类型列表
    [ObservableProperty]
    private ObservableCollection<string> _protocolTypes = new()
    {
        "无协议", "Modbus", "自定义"
    };
    
    // 当前选择的协议类型
    [ObservableProperty]
    private string _selectedProtocolType = "无协议";
    
    // 当前活动协议
    private ProtocolConfig? _activeProtocol;
    
    // 协议列表
    [ObservableProperty]
    private ObservableCollection<ProtocolConfig> _protocols = new();
    
    // Modbus 配置属性
    [ObservableProperty]
    private ModbusConfig.ModbusMode _modbusMode = ModbusConfig.ModbusMode.RTU;
    
    [ObservableProperty]
    private byte _slaveAddress = 1;
    
    [ObservableProperty]
    private bool _useCrc = true;
    
    [ObservableProperty]
    private int _timeout = 1000;
    
    // 自定义协议配置属性
    [ObservableProperty]
    private string _startDelimiter = string.Empty;
    
    [ObservableProperty]
    private string _endDelimiter = string.Empty;
    
    [ObservableProperty]
    private bool _useChecksum = false;
    
    [ObservableProperty]
    private CustomProtocolConfig.ChecksumMethod _checksumMethod = CustomProtocolConfig.ChecksumMethod.None;
    
    [ObservableProperty]
    private int _packetTimeout = 100;
    
    [ObservableProperty] 
    private bool _isEnabled = true;
    
    // 可用校验方法列表
    [ObservableProperty]
    private ObservableCollection<CustomProtocolConfig.ChecksumMethod> _checksumMethods = new(
        Enum.GetValues(typeof(CustomProtocolConfig.ChecksumMethod)).Cast<CustomProtocolConfig.ChecksumMethod>());
    
    // 可用的Modbus模式列表
    [ObservableProperty]
    private ObservableCollection<ModbusConfig.ModbusMode> _modbusModes = new(
        Enum.GetValues(typeof(ModbusConfig.ModbusMode)).Cast<ModbusConfig.ModbusMode>());
    
    // 提供公共访问方式
    public ProtocolConfig? ActiveProtocol => _activeProtocol;
    
    public ProtocolConfigViewModel(MainWindowViewModel mainViewModel)
    {
        _mainViewModel = mainViewModel;
        
        // 监听协议类型更改
        PropertyChanged += (sender, args) =>
        {
            if (args.PropertyName == nameof(SelectedProtocolType))
            {
                UpdateActiveProtocol();
            }
        };
        
        // 初始化协议
        InitializeProtocols();
    }
    
    private void InitializeProtocols()
    {
        // 添加基本协议
        if (Protocols.Count == 0)
        {
            Protocols.Add(new NoProtocolConfig());
            Protocols.Add(new ModbusConfig());
            Protocols.Add(new CustomProtocolConfig());
        }
        
        // 设置默认协议
        UpdateActiveProtocol();
    }
    
    // 切换协议类型时更新活动协议
    private void UpdateActiveProtocol()
    {
        switch (SelectedProtocolType)
        {
            case "Modbus":
                _activeProtocol = Protocols.FirstOrDefault(p => p.ProtocolType == "Modbus") as ModbusConfig;
                if (_activeProtocol == null)
                {
                    _activeProtocol = new ModbusConfig();
                    Protocols.Add(_activeProtocol);
                }
                
                // 更新UI属性
                var modbus = (ModbusConfig)_activeProtocol;
                ModbusMode = modbus.Mode;
                SlaveAddress = modbus.SlaveAddress;
                UseCrc = modbus.UseCRC;
                Timeout = modbus.Timeout;
                IsEnabled = modbus.IsEnabled;
                break;
                
            case "自定义":
                _activeProtocol = Protocols.FirstOrDefault(p => p.ProtocolType == "Custom") as CustomProtocolConfig;
                if (_activeProtocol == null)
                {
                    _activeProtocol = new CustomProtocolConfig();
                    Protocols.Add(_activeProtocol);
                }
                
                // 更新UI属性
                var custom = (CustomProtocolConfig)_activeProtocol;
                StartDelimiter = custom.StartDelimiter;
                EndDelimiter = custom.EndDelimiter;
                UseChecksum = custom.UseChecksum;
                ChecksumMethod = custom.Method;
                PacketTimeout = custom.PacketTimeout;
                IsEnabled = custom.IsEnabled;
                break;
                
            default: // 无协议
                _activeProtocol = Protocols.FirstOrDefault(p => p.ProtocolType == "None") as NoProtocolConfig;
                if (_activeProtocol == null)
                {
                    _activeProtocol = new NoProtocolConfig();
                    Protocols.Add(_activeProtocol);
                }
                IsEnabled = _activeProtocol.IsEnabled;
                break;
        }
        
        // 更新服务中的活动协议
        ProtocolService.Instance.SetActiveProtocol(_activeProtocol);
        
        // 通知UI更新
        OnPropertyChanged(nameof(IsModbusProtocol));
        OnPropertyChanged(nameof(IsCustomProtocol));
    }
    
    // UI辅助属性
    public bool IsModbusProtocol => SelectedProtocolType == "Modbus";
    public bool IsCustomProtocol => SelectedProtocolType == "自定义";
    
    // 应用当前UI设置到协议配置
    [RelayCommand]
    private void ApplySettings()
    {
        if (_activeProtocol == null) return;
        
        _activeProtocol.IsEnabled = IsEnabled;
        
        switch (_activeProtocol.ProtocolType)
        {
            case "Modbus":
                var modbus = (ModbusConfig)_activeProtocol;
                modbus.Mode = ModbusMode;
                modbus.SlaveAddress = SlaveAddress;
                modbus.UseCRC = UseCrc;
                modbus.Timeout = Timeout;
                
                // 序列化存储
                _mainViewModel.SaveModbusSettings(modbus);
                break;
                
            case "Custom":
                var custom = (CustomProtocolConfig)_activeProtocol;
                custom.StartDelimiter = StartDelimiter;
                custom.EndDelimiter = EndDelimiter;
                custom.UseChecksum = UseChecksum;
                custom.Method = ChecksumMethod;
                custom.PacketTimeout = PacketTimeout;
                
                // 序列化存储
                _mainViewModel.SaveCustomProtocolSettings(custom);
                break;
        }
        
        // 更新服务中的活动协议
        ProtocolService.Instance.SetActiveProtocol(_activeProtocol);
        
        // 通知保存
        _mainViewModel.LogEntries.Add($"[INFO] 已应用 {SelectedProtocolType} 协议配置");
    }
    
    // 重置当前协议设置
    [RelayCommand]
    private void ResetSettings()
    {
        switch (SelectedProtocolType)
        {
            case "Modbus":
                ModbusMode = ModbusConfig.ModbusMode.RTU;
                SlaveAddress = 1;
                UseCrc = true;
                Timeout = 1000;
                break;
                
            case "自定义":
                StartDelimiter = string.Empty;
                EndDelimiter = string.Empty;
                UseChecksum = false;
                ChecksumMethod = CustomProtocolConfig.ChecksumMethod.None;
                PacketTimeout = 100;
                break;
        }
        
        IsEnabled = true;
        _mainViewModel.LogEntries.Add($"[INFO] 已重置 {SelectedProtocolType} 协议配置");
    }
} 